//
//  JHContactViewController.m
//  JHChat
//
//  Created by JiaHao on 2/22/15.
//  Copyright (c) 2015 JiaHao. All rights reserved.
//

#import "JHContactViewController.h"
#import "JHContactCell.h"
#import "JHChineseString.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface JHContactViewController ()<UITableViewDataSource,UITableViewDelegate,NSFetchedResultsControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property (strong,nonatomic) NSMutableArray *contactList;
@property (strong,nonatomic) NSMutableArray *indexArray;
@property (strong,nonatomic) NSMutableArray *sortArray;


@property (strong, nonatomic) XMPPStream * xmppStream;
@property (strong,nonatomic) XMPPRoster *xmppRoster;
@property (nonatomic, strong)   NSFetchedResultsController *fetchedResultsController;

@end

@implementation JHContactViewController

-(NSMutableArray *)sortArray
{
    if (!_sortArray) {
        _sortArray = [NSMutableArray new];
    }
    return _sortArray;
}

-(NSMutableArray *)indexArray
{
    if(!_indexArray){
        _indexArray = [NSMutableArray new];
    }
    return _indexArray;
}

-(NSMutableArray *)contactList
{
    if (!_contactList) {
        _contactList = [NSMutableArray new];
    }
    return _contactList;
}

////获取服务器上所有好友列表
//- (void)FetchFriends
//{
//    NSError *error = [[NSError alloc] init];
//    NSXMLElement *query = [[NSXMLElement alloc] initWithXMLString:@"<query xmlns='jabber:iq:roster'/>"error:&error];
//    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
//    [iq addAttributeWithName:@"type" stringValue:@"get"];
//    [iq addAttributeWithName:@"id" stringValue:@"ANY_ID_NAME"];
//    [iq addAttributeWithName:@"from" stringValue:@"ANY_ID_NAME@weejoob.info"];
//    [iq addChild:query];
//    [self.xmppStream sendElement:iq];
//}


//- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
//{
//    [self.FriendArray removeAllObjects];
//    NSXMLElement *queryElement = [iq elementForName: @"query" xmlns: @"jabber:iq:roster"];
//    if (queryElement)
//    {
//        NSArray *itemElements = [queryElement elementsForName: @"item"];
//        for (int i=0; i<[itemElements count]; i++)
//        {
//            NSLog(@"Friend: %@",[[itemElements[i] attributeForName:@"jid"]stringValue]);
//            NSString *jid = [[itemElements[i] attributeForName:@"jid"]stringValue];
//            XMPPJID *xmppJID = [XMPPJID jidWithString:jid];
//            //不是none时可以收发消息
//            NSString *subscription = [[itemElements[i] attributeForName:@"subscription"]stringValue];
//            if (![subscription isEqualToString:@"none"]) {
//                [self.FriendArray addObject:xmppJID];
//            }
//        }
//        [self.tableview reloadData];
//    }
//    return NO;
//}

- (NSFetchedResultsController *)fetchedResultsController
{
    if (!_fetchedResultsController) {
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject"
                                                  inManagedObjectContext:[[JHXMPPManager sharedManager] managedObjectContext_roster]];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subscription != 'none' AND streamBareJidStr == %@",[JHXMPPManager sharedManager].myStreamBareJidStr];
        NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];
        NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, nil];
        
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:entity];
        [fetchRequest setPredicate:predicate];
        [fetchRequest setSortDescriptors:sortDescriptors];
        
        _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                        managedObjectContext:[[JHXMPPManager sharedManager] managedObjectContext_roster]
                                                                          sectionNameKeyPath:nil
                                                                                   cacheName:nil];
        [_fetchedResultsController setDelegate:self];
    }
    
    return _fetchedResultsController;
}

-(void)viewWillAppear:(BOOL)animated
{
    [self.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self.xmppStream removeDelegate:self];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableview.sectionIndexColor = [UIColor brownColor];
    self.tableview.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableview.separatorInset = UIEdgeInsetsMake(0, -5, 0, 0);
    

    self.xmppStream = [[JHXMPPManager sharedManager] xmppStream];
    self.xmppRoster = [[JHXMPPManager sharedManager] xmppRoster];
    [self.xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self fetchFriends];

}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self fetchFriends];
}

-(void)fetchFriends
{
    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        
    }else{
        [self pickBothFriendFromRosterArray:[self.fetchedResultsController fetchedObjects]];
    }
}

- (void)pickBothFriendFromRosterArray:(NSArray *)dataArray
{
    // 筛选出好友
    NSMutableArray *newDataArray = [NSMutableArray arrayWithCapacity:dataArray.count];
    for (XMPPUserCoreDataStorageObject *user in dataArray) {
        if ([user.subscription isEqualToString:@"both"]) {
            [newDataArray addObject:user];
        }
    }
    
    NSMutableArray *nameArray = [NSMutableArray new];
    for (XMPPUserCoreDataStorageObject *object in newDataArray) {
        [nameArray addObject:object.displayName];
    }
    
    self.indexArray = [JHChineseString IndexArray:nameArray];
    self.sortArray = [JHChineseString LetterSortArray:nameArray];
    
    NSMutableArray *tempArray = [NSMutableArray new];
    for (NSMutableArray *section in self.sortArray) {
        NSMutableArray *arr = section.mutableCopy;
        for (NSString *str in section) {
            for (id user in newDataArray) {
                if ([user isKindOfClass:[XMPPUserCoreDataStorageObject class]]) {
                    XMPPUserCoreDataStorageObject *temp = user;
                    if ([str isEqualToString:temp.displayName]) {
                        [arr replaceObjectAtIndex:[section indexOfObject:str] withObject:temp];
                    }
                }
            }
        }
        [tempArray addObject:arr];
    }
    self.contactList = tempArray;
    [self.tableview reloadData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    [headerView setBackgroundColor:RGB(238, 238, 238)];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 25)];
    label.text = self.indexArray[section];
    label.textColor = [UIColor lightGrayColor];
    [headerView addSubview:label];
    return headerView;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.indexArray;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.indexArray[section];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.contactList.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *arr = [self.contactList objectAtIndex:section];
    return arr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JHContactCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JHContactCell"];
    id temp = self.contactList[indexPath.section][indexPath.row];
    if ([temp isKindOfClass:[XMPPUserCoreDataStorageObject class]]) {
        XMPPUserCoreDataStorageObject *user = self.contactList[indexPath.section][indexPath.row];
        cell.friendNameLabel.text = [user displayName];
        [cell.avatarImageView setImageWithURL:nil placeholderImage:[UIImage imageNamed:@"head_s"]];
    }
    
    return cell;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
